package cn.xuexiluxian.open.framework.security.filter;

import cn.xuexiluxian.open.common.utils.AesUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JSON登录
 */
public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    private boolean postOnly = true;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String contentType = request.getContentType();
        if(contentType == null) {
            contentType = "";
        }
        contentType = contentType.toUpperCase();
        String applicationJsonValue = MediaType.APPLICATION_JSON_VALUE;
        applicationJsonValue = applicationJsonValue.toUpperCase();
        if(contentType.startsWith(applicationJsonValue)){//如果是json传递数据
            String username = null;
            String password = null;
            try {
                JSONObject user = new ObjectMapper().readValue(request.getInputStream(), JSONObject.class);
                username = user.getString("username");
                password = user.getString("password");
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (username == null) {
                username = "";
            }

            if (password == null) {
                password = "";
            }

            username = username.trim();

            username = AesUtil.decrypt(username);
            password = AesUtil.decrypt(password);

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            this.setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request, response);
    }
}
